import PropTypes from 'prop-types';
import React from 'react';

export interface ICheckboxProps {
  name?: string;
  title?: string;
  defaultChecked?: boolean;
  checked?: boolean;
  className?: string;
  style?: React.CSSProperties;
  onToggle?: (checked: boolean) => void;
}

export interface ICheckboxState {
  checked?: boolean;
}
export class Checkbox extends React.Component<ICheckboxProps, ICheckboxState> {
  public static propTypes = {
    name: PropTypes.string,
    title: PropTypes.string,
    defaultChecked: PropTypes.bool,
    checked: PropTypes.bool,
    className: PropTypes.string,
    onToggle: PropTypes.func,
  };
    // 如果传入了外部props，更新到state
  public static getDerivedStateFromProps(nextProps: ICheckboxProps, prevState: ICheckboxState) {
    if (nextProps.checked !== undefined) {
      return {
        checked: nextProps.checked,
      };
    }
    return null;
  }

  constructor(props: ICheckboxProps) {
    super(props);
    this.state = {
      checked: props.defaultChecked || props.checked || false,
    };
    this.handleToggle = this.handleToggle.bind(this);
  }

  public handleToggle() {
    if (this.props.onToggle) {
      this.props.onToggle(!this.state.checked);
    }

    // 受控
    if (this.props.checked === undefined) {
      this.setState({
        checked: !this.state.checked,
      });
    }
  }

  public render() {
    let classString = '';
    const className = this.props.className || '';
    classString = `br-checkbox ${this.state.checked ? 'br-checkbox--checked' : ''} ${className}`;
    return (
      <div className={classString} style={this.props.style} onClick={this.handleToggle}>
        <span className="br-checkbox__icon" > {this.props.children} </span>
        <input type="br-checkbox" name={this.props.name} checked={this.state.checked} className="hidden" readOnly />
        <span className="br-checkbox__title">{this.props.title || ''}</span>
      </div>
    );
  }
}
